﻿#region namespaces

using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using SLIITPro.Data.Extension;
// This is reference from the facebook dll
using Facebook.Rest;
using Facebook.Session;

#endregion

namespace SLIITPro.Controls
{
    public partial class Siteheader : System.Web.UI.UserControl
    {
        private Api _facebookApi;
        private ConnectSession _connectSession;
        protected void Page_Load(object sender, EventArgs e)
        {
            _connectSession = new ConnectSession(ConfigurationManager.AppSettings["FBApiKey"],
                                                ConfigurationManager.AppSettings["FBSecret"]);
            _facebookApi = new Api(_connectSession);
            Session["facebookApi"] = _facebookApi;
            if (!IsPostBack)
                LiteralFBLogin.Text = "<fb:login-button length=\"long\" onlogin=\"window.location.reload()\" autologoutlink=\"true\"></fb:login-button>";
            if (Page.User.Identity.IsAuthenticated)
            {
                hypLogout.NavigateUrl = Core.CoreSettings.AbsoluteUrl + "Default.aspx?logoff";
                hypLogout.Text = "Logout";
            }
        }

        private string GetRoles()
        {
            if (Page.User.IsInRole("administrator")) return "Administrator";
            if (Page.User.IsInRole("information")) return "Information User";
            if (Page.User.IsInRole("content")) return "Content User";
            if (Page.User.IsInRole("business")) return "Business User";
            return string.Empty;
        }

        private Data.Entity.Users _users;
        private UserExtension _extension;
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            Page.Validate("login");
            if (string.IsNullOrEmpty(txtPnlUsername.Text) || string.IsNullOrEmpty(txtPnlPassword.Text))
            {
                lblLoginText.Text = "Username and Password Required";
                return;
            }

            DataRow row;
            _extension = new UserExtension();
            if (!_extension.AuthenticateUser(txtPnlUsername.Text.Trim(), txtPnlPassword.Text.Trim(), out row))
            {
                lblLoginText.Text = "Invalide login attempt...Try again";
                return;
            }
            _users = new Data.Entity.Users(row);
            var muser = Membership.GetUser(txtPnlUsername.Text);
            if (muser == null) return;
            if (_users.IsActivated)
            {
                SetToken();
                Response.Redirect(Request.QueryString["ReturnUrl"] ?? "Default.aspx", true);
            }
            else
            {
                lblLoginText.Text = string.Format("User {0} {1} not activated yet", _users.FirstName, _users.LastName);
            }
        }

        private void SetToken()
        {
            var authTicket = new FormsAuthenticationTicket(_users.UserId, _users.Email, DateTime.Now,
                                                                   DateTime.Now.AddMinutes(60),
                                                                   false, _users.UserType);

            var encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            var authenticateCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            Response.Cookies.Add(authenticateCookie);
            Session.RemoveAll();
        }
    }
}